package com.hydra.gateway.utils;

import com.hydra.base.utils.FormatUtil;
import com.hydra.base.utils.JsonUtil;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


public class ResponseUtil {

    public static Mono<Void> writeResponseMono(ServerHttpRequest request, ServerHttpResponse response, HttpStatus httpStatus, String message){
        response.setStatusCode(httpStatus);
        HttpHeaders headers = response.getHeaders();
        headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        //浏览器跨域处理
        headers.setAccessControlAllowOrigin("*");
        headers.setAccessControlAllowCredentials(true);

        Map<String, Object> map = new HashMap<>();
        map.put("timestamp", FormatUtil.formatDateTime(new Date()));
        map.put("status", httpStatus.value());
        map.put("error", message);

        String requestURI = request.getURI().getPath();
        map.put("path", requestURI);

        String body = JsonUtil.toJsonString(map);
        DataBuffer dataBuffer = response.bufferFactory().wrap(body.getBytes(StandardCharsets.UTF_8));

        return response.writeWith(Mono.just(dataBuffer));
    }

}
